<?php
/**
 *
 * User: 梁晓伟  lxw11109@gmail.com
 * Date: 2017-11-05
 * Time: 16:37
 */

namespace App\Http\Controllers\Api\V1\Manager\Supplier;


use App\Http\Controllers\Controller;
use App\Models\Brand;
use App\Models\District;
use App\Models\ExpressfeeCity;
use App\Models\ExpressfeeCityC;
use App\Models\Good;
use App\Models\GoodsOneType;
use App\Models\GoodsStock;
use App\Models\GoodsTwoType;
use App\Models\Order;
use App\Models\OrderDetail;
use App\Models\Supplier;
use App\Models\Expressfee;
use App\Models\UserHome;
use App\Models\UserStatistics;
use App\Models\VipLog;
use DateTime;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;

class SupplierFreightController extends Controller
{
    private $namespace = "App\Http\Controllers\Api\V1\Manager\Supplier\SupplierFreightController";

    public function index(Request $request)
    {
        $freightName = $request->freightName;
        $supplierId = $request->supplierId;
        $sql = Expressfee::select('id', 'name', 'supplier_id')
            ->where('supplier_id', $supplierId)
            ->where('is_del', 0);
        if (isset($freightName)) {
            $sql->where('name', 'like', "%$freightName%");
        }
        $supplierList = $sql->orderByDesc('id')
            ->get()
            ->toArray();
        $data['freightList'] = $supplierList;
        foreach ($data['freightList'] as $key => $value) {
        }
        $data['totalNum'] = count($supplierList);
        return $this->apiResponse($data);
    }

    public function store(Request $request)
    {
        if (!$this->permissionAuthenticate($request->RESOURCE, "这里输入需要的资源组权限")) {
            return $this->apiResponse('', config('errorLiu.NINZHANWUGAIJIEKOUQUANX'));
        }
        $id = $request->id;
        //是否强制修改 1是
//        $force = $request->force;
        $content = "";
//        if ($force) {
//            $content = "强制";
//        }
        $data = $request->only('supplier_id', 'name');
        if (!isset($data['supplier_id']) || !isset($data['name'])) {
            return $this->apiResponse('', config('errorLiu.NOTCANSHUID'));
        }
        $storeNum = Expressfee::where('name', $data['name'])->where('supplier_id', $data['supplier_id'])->where('id', '!=', $id)->count();
        if ($storeNum) {
            return $this->apiResponse('', config('errorLiu.GAIYUNFEIMOBVANNUBNGCGEBFGVYJEJK'));
        }
        if ($id) {
//            if ($data['type'] == 1) {
//                $num = Good::from((new Good())->getTable() . ' as t1')
//                    ->join((new GoodsStock())->getTable() . ' as t2', 't1.id', '=', 't2.goods_id')
//                    ->where('t1.expressfee_id', $id)
//                    ->where('t1.status', '!=', 2)
//                    ->where('t2.zhongliang', 0)
//                    ->get()
//                    ->toArray();
//                if (isset($num[0])) {
//                    return $this->apiResponse('', config('errorLiu.CUNZAIZHONGLIANGLINGD'));
//                }
//            }
//            unset($data['supplierId']);
//            $expressfee = Expressfee::where('id', $id)->first();
//            if ($expressfee['type'] == $data['type']) {
//                Expressfee::where('id', $id)->update($data);
//                return $this->apiResponse(true);
//            }
//            $num = Good::where('status', '!=', 2)->where('expressfee_id', $id)->count();
//            if ($num && !$force) {
//                return $this->apiResponse('', config('errorLiu.GAIYUNFEIMOBANYOUZHENGZAISHIYONG'));
//            }
//            Good::where('status', '!=', 2)->where('expressfee_id', $id)->update(['status' => 2]);
            Expressfee::where('id', $id)->update($data);
//            if ($data['type'] == 1) {
//                $unit = 0;
//            } else {
//                $unit = 1;
//            }
            //ExpressfeeCity::where('expressfeeid', $id)->where('is_free', 0)->update(['unit' => $unit]);
            $content .= "修改";
        } else {
            $id = Expressfee::insertGetId($data);
            $content .= "新增";
        }
//        ExpressfeeCity::where('expressfeeid', $id)->delete();
//        ExpressfeeCity::where('expressfeeid', $id)->update(['expressfeecity_b_id' => null]);
        //添加管理员日志开始
        $url = $this->namespace . "/store";
        $title = $content;
        $content .= "了id为【" . $id . "】的运费模板,内容为【" . json_encode($data) . "】";
        $this->addAdminLog($request->ADMINID, $request->ADMINUSERNAME, $url, "运费规则模块", $title, $content, $request->getClientIp());
        //添加管理员日志结束
        return $this->apiResponse(true);
    }

    public function destroy(Request $request, $id)
    {
        if (!$this->permissionAuthenticate($request->RESOURCE, "这里输入需要的资源组权限")) {
            return $this->apiResponse('', config('errorLiu.NINZHANWUGAIJIEKOUQUANX'));
        }
        //是否强制删除 1是
        $force = $request->force;
        $content = "";
        if ($force) {
            $content = "强制";
        }
        $expressfee = Expressfee::where('id', $id)->first();
        $num = Good::where('status', '!=', 2)->where('expressfee_id', $id)->count();
        if ($num && !$force) {
            return $this->apiResponse('', config('errorLiu.GAIYUNFEIMOBANYOUZHENGZAISHIYONG'));
        }
        Good::where('status', '!=', 2)->where('expressfee_id', $id)->update(['status' => 2]);
        Expressfee::where('id', $id)->delete();
        ExpressfeeCity::where('expressfeeid', $id)->delete();
        //添加管理员日志开始
        $url = $this->namespace . "/destroy";
        $title = "删除";
        $content .= "删除了id为【" . $id . "】的运费模板,内容为【" . json_encode($expressfee) . "】";
        $this->addAdminLog($request->ADMINID, $request->ADMINUSERNAME, $url, "运费规则模块", $title, $content, $request->getClientIp());
        //添加管理员日志结束
        return $this->apiResponse(true);
    }


    public function getArea(Request $request)
    {
        $expressfeeid = $request->expressfeeid;
        $expressfeecity_b_id = $request->expressfeecity_b_id ?: 0;
        $provinceList = District::select('t1.district_id', 't1.district', 't2.id', 't2.expressfeecity_b_id')
            ->from((new District())->getTable() . ' as t1')
            ->leftJoin((new ExpressfeeCityC())->getTable() . ' as t2', function ($query) use ($expressfeeid) {
                $query->on('t1.district_id', '=', 't2.area_id')
                    ->where('t2.expressfeeid', $expressfeeid);
            })
            ->where('t1.level', 1)
            ->orderBy('district_id')
            ->get()->toArray();
        foreach ($provinceList as $k => $val) {
            $provinceList[$k]['is_use'] = 0;
            $provinceList[$k]['is_role'] = 1;
            if (isset($val['id'])) {
                $provinceList[$k]['is_use'] = 1;
            }
            unset($provinceList[$k]['id']);
            if ($expressfeecity_b_id) {
                if ($val['expressfeecity_b_id']) {
                    if ($val['expressfeecity_b_id'] != $expressfeecity_b_id) {
                        $provinceList[$k]['is_role'] = 0;
                    }
                }
            }
            unset($provinceList[$k]['expressfeecity_b_id']);
            $data[] = $provinceList[$k];
        }
        return $this->apiResponse($data);
//        $districtList = District::select('t1.district_id', 't1.district', 't2.id')
//            ->from((new District())->getTable() . ' as t1')
//            ->leftJoin((new ExpressfeeCityC())->getTable() . ' as t2', function ($query) use ($expressfeeid) {
//                $query->on('t1.district_id', '=', 't2.area_id')
//                    ->where('t2.expressfeeid', $expressfeeid);
//            })
//            ->where('t1.level', 0)
//            ->orderBy('district_id')
//            ->get()->toArray();
//        $data = [];
//        foreach ($districtList as $key => $value) {
////            $districtList[$key]['is_use'] = 0;
////            if(isset($value['id'])){
////                $districtList[$key]['is_use'] = 1;
////            }
//            unset($districtList[$key]['id']);
//            $provinceList = District::select('t1.district_id', 't1.district', 't2.id', 't2.expressfeecity_b_id')
//                ->from((new District())->getTable() . ' as t1')
//                ->leftJoin((new ExpressfeeCityC())->getTable() . ' as t2', function ($query) use ($expressfeeid) {
//                    $query->on('t1.district_id', '=', 't2.area_id')
//                        ->where('t2.expressfeeid', $expressfeeid);
//                })
//                ->where('t1.pid', $value['district_id'])
//                ->orderBy('district_id')
//                ->get()->toArray();
//            $districtList[$key]['is_use'] = 0;
//            foreach ($provinceList as $k => $val) {
//                $provinceList[$k]['is_use'] = 0;
//                if (isset($val['id'])) {
//                    $provinceList[$k]['is_use'] = 1;
//                    $districtList[$key]['is_use'] = 1;
//                }
//                unset($provinceList[$k]['id']);
//                if (!$val['expressfeecity_b_id']) {
//                    $provinceList[$k]['is_role'] = 0;
//                } else {
//                    $provinceList[$k]['is_role'] = 1;
//                }
//                unset($provinceList[$k]['expressfeecity_b_id']);
//                $data[] = $provinceList[$k];
//            }
//            $districtList[$key]['districtList'] = $provinceList;
//        }
//        return $this->apiResponse($data);
    }

//    public function setAreaNo(Request $request)
//    {
//        if (!$this->permissionAuthenticate($request->RESOURCE, "这里输入需要的资源组权限")) {
//            return $this->apiResponse('', config('errorLiu.NINZHANWUGAIJIEKOUQUANX'));
//        }
//        $id = $request->id;
//        $district_id = $request->district_id;
//        $district_id = explode(';', $district_id);
//        $expressfee = Expressfee::select()->where('id', $id)->first();
//        if($expressfee['type'] == 1){
//            $unit = 0;
//        }else{
//            $unit = 1;
//        }
//        if ($expressfee) {
//            $areaIdList = [];
//            $level1 = District::select('pid')->where('level', 1)->whereIn('district_id', $district_id)->groupBy('pid')->get()->toArray();
//            $u2 = [];
//            foreach ($district_id as $k => $v) {
//                $areaIdList[] = $v;
//                $u2[$k]['level'] = 1;
//                $u2[$k]['area_id'] = $v;
//                $u2[$k]['expressfeeid'] = $id;
//                $u2[$k]['supplier_id'] = $expressfee['supplier_id'];
//                $u2[$k]['unit'] = $unit;
//            }
//            $u1 = [];
//            $areaList = ExpressfeeCity::where('supplier_id', $expressfee['supplier_id'])->where('expressfeeid', $id)->where('level', 0)->get()->toArray();
//            $level0IdList = [];
//            foreach ($level1 as $key => $value) {
//                unset($v);
//                $isInsert = 1;
//                foreach ($areaList as $v) {
//                    if ($v['area_id'] == $value['pid']) {
//                        $isInsert = 0;
//                        $level0IdList[] = $v['area_id'];
//                        break;
//                    }
//                }
//                if ($isInsert) {
//                    $u1[$key]['level'] = 0;
//                    $u1[$key]['area_id'] = $value['pid'];
//                    $u1[$key]['expressfeeid'] = $id;
//                    $u1[$key]['supplier_id'] = $expressfee['supplier_id'];
//                    $u1[$key]['unit'] = $unit;
//                }
//            }
//            ExpressfeeCity::where('supplier_id', $expressfee['supplier_id'])->where('expressfeeid', $id)->whereNotIn('area_id', $level0IdList)->where('is_free', 0)->delete();
//            ExpressfeeCity::where('supplier_id', $expressfee['supplier_id'])->where('expressfeeid', $id)->where('is_free', 1)->whereIn('area_id', $areaIdList)->delete();
//            ExpressfeeCity::insert($u1);
//            ExpressfeeCity::insert($u2);
//        }
//        //添加管理员日志开始
//        $url = $this->namespace . "/setAreaNo";
//        $title = "修改";
//        $content = "给id为【" . $id. "】的运费模板设置非免邮地区,内容为【".json_encode($district_id)."】";
//        $this->addAdminLog($request->ADMINID, $request->ADMINUSERNAME, $url, "运费规则模块", $title, $content, $request->getClientIp());
//        //添加管理员日志结束
//        return $this->apiResponse(true);
//    }


    public function setAreaNo(Request $request)
    {
        if (!$this->permissionAuthenticate($request->RESOURCE, "这里输入需要的资源组权限")) {
            return $this->apiResponse('', config('errorLiu.NINZHANWUGAIJIEKOUQUANX'));
        }
        $id = $request->id;
        $district_id = $request->district_id;
        $district_id = explode(';', $district_id);
        $expressfee = Expressfee::select()->where('id', $id)->first();
        if ($expressfee) {
            $areaIdList = [];
            $uList = [];
            $areaList = ExpressfeeCityC::where('supplier_id', $expressfee['supplier_id'])->where('expressfeeid', $id)->get()->toArray();
            foreach ($district_id as $key => $value) {
                unset($v);
                $isInsert = 1;
                foreach ($areaList as $v) {
                    if ($v['area_id'] == $value) {
                        $isInsert = 0;
                        $areaIdList[] = $v['area_id'];
                        break;
                    }
                }
                if ($isInsert) {
                    $uList[$key]['area_id'] = $value;
                    $uList[$key]['expressfeeid'] = $id;
                    $uList[$key]['supplier_id'] = $expressfee['supplier_id'];
                    $uList[$key]['type'] = $expressfee['type'];
                }
            }
            ExpressfeeCityC::where('supplier_id', $expressfee['supplier_id'])->where('expressfeeid', $id)->whereNotIn('area_id', $areaIdList)->delete();
            ExpressfeeCityC::insert($uList);
        }
        //添加管理员日志开始
        $url = $this->namespace . "/setAreaNo";
        $title = "修改";
        $content = "给id为【" . $id . "】的运费模板设置非免邮地区,内容为【" . json_encode($district_id) . "】";
        $this->addAdminLog($request->ADMINID, $request->ADMINUSERNAME, $url, "运费规则模块", $title, $content, $request->getClientIp());
        //添加管理员日志结束
        return $this->apiResponse(true);
    }

    public function setAreaYes(Request $request)
    {
//        if (!$this->permissionAuthenticate($request->RESOURCE, "这里输入需要的资源组权限")) {
//            return $this->apiResponse('', config('errorLiu.NINZHANWUGAIJIEKOUQUANX'));
//        }
//        $id = $request->id;
//        $district_id = $request->district_id;
//        $district_id = explode(';', $district_id);
//        $expressfee = Expressfee::select()->where('id', $id)->first();
//        if ($expressfee) {
//            $areaIdList = [];
//            $u2 = [];
//            foreach ($district_id as $k => $v) {
//                $areaIdList[] = $v;
//                $u2[$k]['level'] = 1;
//                $u2[$k]['area_id'] = $v;
//                $u2[$k]['expressfeeid'] = $id;
//                $u2[$k]['supplier_id'] = $expressfee['supplier_id'];
//                $u2[$k]['is_free'] = 1;
//            }
//            ExpressfeeCity::where('supplier_id', $expressfee['supplier_id'])->where('expressfeeid', $id)->where('is_free', 0)->whereIn('area_id', $areaIdList)->delete();
//            ExpressfeeCity::insert($u2);
//        }
//        //添加管理员日志开始
//        $url = $this->namespace . "/setAreaYes";
//        $title = "修改";
//        $content = "给id为【" . $id. "】的运费模板设置免邮地区,内容为【".json_encode($district_id)."】";
//        $this->addAdminLog($request->ADMINID, $request->ADMINUSERNAME, $url, "运费规则模块", $title, $content, $request->getClientIp());
//        //添加管理员日志结束
//        return $this->apiResponse(true);
    }

    public function getRule(Request $request)
    {
        $id = $request->id;
        $areaList = ExpressfeeCity::select('id', 'id as district_id', 'id as area', 'unit', 'type', 'type as fweight', 'type as tweight', 'freightList')->where('expressfeeid', $id)->get()->toArray();
        foreach ($areaList as $key => $value) {
            $areaList[$key]['fweight'] = [];
            $areaList[$key]['tweight'] = [];
            if (isset($value['freightList'])) {
                $freightList = json_decode($value['freightList']);
                $areaList[$key]['fweight'] = $freightList->fweight;
                $areaList[$key]['tweight'] = $freightList->tweight;
            }
            $areaLists = District::select('t1.district_id', 't1.district')
                ->from((new District())->getTable() . ' as t1')
                ->join((new ExpressfeeCityC())->getTable() . ' as t2', function ($query) use ($value) {
                    $query->on('t1.district_id', '=', 't2.area_id')
                        ->where('t2.expressfeecity_b_id', $value['id']);
                })
                ->orderBy('district_id')
                ->get()->toArray();
            $area = null;
            $district_id = null;
            foreach ($areaLists as $val) {
                if (isset($area)) {
                    $area .= "、" . $val['district'];
                } else {
                    $area = $val['district'];
                }
                if (isset($district_id)) {
                    $district_id .= ";" . $val['district_id'];
                } else {
                    $district_id = $val['district_id'];
                }
            }
            $areaList[$key]['district_id'] = $district_id;
            $areaList[$key]['area'] = $area;
            unset($areaList[$key]['freightList']);
        }
        return $this->apiResponse($areaList);
    }

    public function setRule(Request $request)
    {
        if (!$this->permissionAuthenticate($request->RESOURCE, "这里输入需要的资源组权限")) {
            return $this->apiResponse('', config('errorLiu.NINZHANWUGAIJIEKOUQUANX'));
        }
        //是否强制删除 1是
        $force = $request->force?:0;
        $content = "";
        if ($force) {
            $content = "强制";
        }
        $expressfeeid = $request->expressfeeid;
        $id = $request->id;
        $data = $request->only('expressfeeid', 'id', 'district_id', 'unit', 'type', 'fweight', 'tweight');
        //$input_val = json_decode($val);
        $expressfee = Expressfee::select()->where('id', $expressfeeid)->first();
        if ($expressfee) {
            try {
                \DB::beginTransaction();
                $weight = 0;
                //return var_dump($expressfeeCityCList);
                $freightList = [];
                $freightList['fweight'] = $data['fweight'];
                $freightList['tweight'] = $data['tweight'];
                $district_id = explode(';', $data['district_id']);
                if (isset($district_id[0])) {
                    if ($id) {
                        $expressfeecity_b_id = $id;
                        $old_expressfeeCity = ExpressfeeCity::where('id', $id)->first();
                        ExpressfeeCity::where('id', $id)->update([
                            "type" => $data['type'],
                            "unit" => $data['unit'],
                            "freightList" => json_encode($freightList)
                        ]);
                        if($old_expressfeeCity['unit'] != $data['unit']){
                            if ($data['unit'] == 0) {
                                $weight = 1;
                            }
                        }
                    } else {
                        if ($data['unit'] == 0) {
                            $weight = 1;
                        }
                        $expressfeeCity = [];
                        $expressfeeCity['supplier_id'] = $expressfee['supplier_id'];
                        $expressfeeCity['expressfeeid'] = $expressfee['id'];
                        $expressfeeCity['unit'] = $data['unit'];
                        $expressfeeCity['type'] = $data['type'];
                        $expressfeeCity['freightList'] = json_encode($freightList);
                        $expressfeecity_b_id = ExpressfeeCity::insertGetId($expressfeeCity);
                    }
                    ExpressfeeCityC::where('expressfeecity_b_id', $expressfeecity_b_id)->update(['expressfeecity_b_id' => null]);
                    $expressfeeCityCList = ExpressfeeCityC::where('supplier_id', $expressfee['supplier_id'])->where('expressfeeid', $expressfeeid)->get()->toArray();
                    unset($k);
                    unset($v);
                    $uList = [];
                    foreach ($district_id as $k => $v) {
                        $insert = 1;
                        foreach ($expressfeeCityCList as $item) {
                            if ($v == $item['area_id']) {
                                $insert = 0;
                                ExpressfeeCityC::where('id', $item['id'])->update(['expressfeecity_b_id' => $expressfeecity_b_id]);
                                break;
                            }
                        }
                        if ($insert) {
                            $uList[$k]['area_id'] = $v;
                            $uList[$k]['expressfeeid'] = $expressfeeid;
                            $uList[$k]['supplier_id'] = $expressfee['supplier_id'];
                            $uList[$k]['type'] = $expressfee['type'];
                            $uList[$k]['expressfeecity_b_id'] = $expressfeecity_b_id;
                        }
                    }
                    ExpressfeeCityC::insert($uList);
                }
                if ($weight) {
                    $num = Good::select('t1.id')
                        ->from((new Good())->getTable() . ' as t1')
                        ->join((new GoodsStock())->getTable() . ' as t2', 't1.id', '=', 't2.goods_id')
                        ->where('t1.expressfee_id', $expressfeeid)
                        ->where('t1.status', '!=', 2)
                        ->where('t2.zhongliang', 0)
                        ->get()
                        ->toArray();
                    if (isset($num[0])) {
                        if(!$force){
                            return $this->apiResponse('', config('errorLiu.CUNZAIZHONGLIANGLINGD'));
                        }
                        $goodIdList = [];
                        unset($value);
                        foreach ($num as $value){
                            $goodIdList[] = $value['id'];
                        }
                        Good::whereIn('id',$goodIdList)->update(['status'=>2]);
                    }
                }
                //添加管理员日志开始
                $url = $this->namespace . "/setRule";
                $title = "修改";
                $content .= "给id为【" . $id . "】的运费模板设置运费规则,内容为【" . json_encode($data) . "】";
                $this->addAdminLog($request->ADMINID, $request->ADMINUSERNAME, $url, "运费规则模块", $title, $content, $request->getClientIp());
                //添加管理员日志结束
                \DB::commit();
                return $this->apiResponse(true);
            } catch (\Exception $e) {
                \DB::rollback();
                return $this->apiResponse('', config('errorLiu.CAAOZUOSHIBAI'));
            }
        }
        return $this->apiResponse(true);
    }

    public function delRule(Request $request)
    {
        if (!$this->permissionAuthenticate($request->RESOURCE, "这里输入需要的资源组权限")) {
            return $this->apiResponse('', config('errorLiu.NINZHANWUGAIJIEKOUQUANX'));
        }
        $id = $request->id;
        $expressfeeCity = ExpressfeeCity::select()->where('id', $id)->first();
        if ($expressfeeCity) {
            try {
                \DB::beginTransaction();
                ExpressfeeCity::where('id', $id)->delete();
                ExpressfeeCityC::where('expressfeecity_b_id', $id)->update(['expressfeecity_b_id' => null]);
                //添加管理员日志开始
                $url = $this->namespace . "/delRule";
                $title = "删除";
                $content = "删除id为【" . $id . "】的运费模板设置运费规则,内容为【" . json_encode($expressfeeCity) . "】";
                $this->addAdminLog($request->ADMINID, $request->ADMINUSERNAME, $url, "运费规则模块", $title, $content, $request->getClientIp());
                //添加管理员日志结束
                \DB::commit();
                return $this->apiResponse(true);
            } catch (\Exception $e) {
                \DB::rollback();
                return $this->apiResponse('', config('errorLiu.CAAOZUOSHIBAI'));
            }
        }
        return $this->apiResponse(true);
    }

}